// navigation.js - 导航组件 (ES模块)

class Navigation {
    constructor(containerSelector, options = {}) {
        this.container = document.querySelector(containerSelector);
        if (!this.container) return;

        this.options = { ...this.defaultOptions, ...options };
        this.isMobile = window.innerWidth <= this.options.mobileBreakpoint;
        this.menuState = JSON.parse(localStorage.getItem('menuState')) || {};

        this.init();
        this.bindEvents();
    }

    defaultOptions = {
        mobileBreakpoint: 768,
        submenuToggleSpeed: 300,
        rememberState: true,
        hasMobileMenu: true
    };

    init() {
        // 添加图标
        this.addIcons();

        // 初始化移动端菜单
        if (this.options.hasMobileMenu) {
            this.initMobileMenu();
        }

        // 应用保存的菜单状态
        this.applyMenuState();

        // 设置响应式布局
        this.checkResponsive();
    }

    bindEvents() {
        // 菜单项点击事件
        this.container.querySelectorAll('.menu-item').forEach(item => {
            item.addEventListener('click', (e) => this.handleMenuItemClick(e, item));
            // 添加鼠标悬停效果
            item.addEventListener('mouseenter', () => item.classList.add('hover'));
            item.addEventListener('mouseleave', () => item.classList.remove('hover'));
        });

        // 菜单组点击事件（用于展开/折叠子菜单）
        this.container.querySelectorAll('.menu-group > .menu-item').forEach(item => {
            item.addEventListener('click', (e) => this.toggleSubmenu(e, item));
        });

        // 为子菜单项添加点击事件
        this.container.querySelectorAll('.submenu-item').forEach(item => {
            item.addEventListener('click', (e) => {
                // 关闭所有子菜单
                this.container.querySelectorAll('.submenu.expanded').forEach(sub => {
                    sub.classList.remove('expanded');
                });
                // 重置所有图标
                this.container.querySelectorAll('.submenu-toggle-icon').forEach(icon => {
                    icon.className = 'fas fa-chevron-down submenu-toggle-icon rotate-0';
                });
            });
        });

        // 窗口大小变化事件
        window.addEventListener('resize', () => this.checkResponsive());
    }

    addIcons() {
        // 为菜单项添加图标
        const menuItems = this.container.querySelectorAll('.menu-item');
        menuItems.forEach(item => {
            const text = item.textContent.trim();
            let iconClass = 'fa-circle'; // 默认图标

            // 根据菜单项文本设置不同图标
            switch(text) {
                case '欢迎页':
                    iconClass = 'fa-home';
                    break;
                case '员工管理':
                    iconClass = 'fa-users';
                    break;
                case '业务管理':
                    iconClass = 'fa-briefcase';
                    break;
                case '薪酬管理':
                    iconClass = 'fa-money-bill-wave';
                    break;
                case '系统设置':
                    iconClass = 'fa-cog';
                    break;
                case '员工列表':
                    iconClass = 'fa-list';
                    break;
                case '添加员工':
                    iconClass = 'fa-user-plus';
                    break;
                case '业务列表':
                    iconClass = 'fa-th-list';
                    break;
                case '创建业务':
                    iconClass = 'fa-plus-circle';
                    break;
                case '薪酬概览':
                    iconClass = 'fa-chart-bar';
                    break;

                case '用户管理':
                    iconClass = 'fa-user-cog';
                    break;
                case '个人设置':
                    iconClass = 'fa-user-edit';
                    break;

            }

            // 添加FontAwesome图标
            item.innerHTML = `<i class="fas ${iconClass}"></i> <span>${text}</span>`;

            // 如果是菜单组，添加展开/折叠图标
            if (item.parentElement.classList.contains('menu-group')) {
                item.innerHTML += '<i class="fas fa-chevron-down submenu-toggle-icon"></i>';
            }
        });
    }

    initMobileMenu() {
        // 创建移动端菜单按钮
        const menuBtn = document.createElement('button');
        menuBtn.className = 'mobile-menu-btn';
        menuBtn.innerHTML = '<i class="fas fa-bars"></i> 菜单';
        menuBtn.style.cssText = `
            display: none;
            padding: 10px 15px;
            background-color: #4e6ef2;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            margin-bottom: 10px;
        `;

        // 将按钮添加到侧边栏顶部
        this.container.parentNode.insertBefore(menuBtn, this.container);

        // 移动端菜单按钮点击事件
        menuBtn.addEventListener('click', () => {
            this.container.style.display = this.container.style.display === 'block' ? 'none' : 'block';
        });

        this.mobileMenuBtn = menuBtn;
    }

    toggleSubmenu(e, menuItem) {
        // 当点击菜单项或其子元素时都触发
        if (e.target.closest('.menu-item') === menuItem || e.currentTarget === menuItem) {
            e.preventDefault();
            e.stopPropagation();

            const menuGroup = menuItem.parentElement;
            const submenu = menuGroup.querySelector('.submenu');
            const icon = menuItem.querySelector('.submenu-toggle-icon');

            if (submenu) {
                // 使用CSS过渡动画
                const isExpanded = submenu.classList.contains('expanded');

                if (isExpanded) {
                    submenu.classList.remove('expanded');
                    if (icon) icon.className = 'fas fa-chevron-down submenu-toggle-icon rotate-0';
                } else {
                    submenu.classList.add('expanded');
                    if (icon) icon.className = 'fas fa-chevron-down submenu-toggle-icon rotate-180';
                }

                // 保存菜单状态
                if (this.options.rememberState) {
                    const menuText = menuItem.textContent.trim();
                    this.menuState[menuText] = !isExpanded;
                    localStorage.setItem('menuState', JSON.stringify(this.menuState));
                }
            }
        }
    }

    applyMenuState() {
        // 应用保存的菜单状态
        for (const [menuText, isExpanded] of Object.entries(this.menuState)) {
            // 查找包含特定文本的菜单项
            const menuItems = this.container.querySelectorAll('.menu-item');
            let foundMenuItem = null;

            for (const item of menuItems) {
                const span = item.querySelector('span');
                if (span && span.textContent.trim() === menuText) {
                    foundMenuItem = item;
                    break;
                }
            }

            if (foundMenuItem && foundMenuItem.parentElement.classList.contains('menu-group')) {
                const submenu = foundMenuItem.parentElement.querySelector('.submenu');
                const icon = foundMenuItem.querySelector('.submenu-toggle-icon');

                if (submenu && icon) {
                    if (isExpanded) {
                        submenu.classList.add('expanded');
                        icon.className = 'fas fa-chevron-down submenu-toggle-icon rotate-180';
                    } else {
                        submenu.classList.remove('expanded');
                        icon.className = 'fas fa-chevron-down submenu-toggle-icon rotate-0';
                    }
                }
            }
        }
    }

    handleMenuItemClick(e, menuItem) {
        // 如果不是外部链接，阻止默认行为
        if (menuItem.getAttribute('href') === '#') {
            e.preventDefault();
        }

        // 移除所有active类
        this.container.querySelectorAll('.menu-item, .submenu-item').forEach(item => {
            item.classList.remove('active');
        });

        // 给当前点击项添加active类
        menuItem.classList.add('active');

        // 如果是子菜单项，也给父菜单添加active类
        if (menuItem.classList.contains('submenu-item')) {
            const parentMenuItem = menuItem.closest('.menu-group').querySelector('.menu-item');
            if (parentMenuItem) {
                parentMenuItem.classList.add('active');
            }
        }
    }

    checkResponsive() {
        const wasMobile = this.isMobile;
        this.isMobile = window.innerWidth <= this.options.mobileBreakpoint;

        if (this.isMobile !== wasMobile) {
            if (this.isMobile) {
                // 切换到移动端视图
                this.container.style.display = 'none';
                if (this.mobileMenuBtn) {
                    this.mobileMenuBtn.style.display = 'block';
                }
            } else {
                // 切换到桌面端视图
                this.container.style.display = 'block';
                if (this.mobileMenuBtn) {
                    this.mobileMenuBtn.style.display = 'none';
                }
            }
        }
    }
}

// 添加contains选择器
Element.prototype.contains = function(text) {
    return this.textContent.includes(text);
};

// 初始化导航
function initNavigation() {
    // 等待DOM加载完成
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', () => new Navigation('.menu'));
    } else {
        new Navigation('.menu');
    }
}

// 添加FontAwesome样式
const fontAwesomeStyle = document.createElement('link');
fontAwesomeStyle.rel = 'stylesheet';
fontAwesomeStyle.href = 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css';
document.head.appendChild(fontAwesomeStyle);

// 自动初始化
if (typeof document !== 'undefined') {
    // 等待DOM加载完成
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initNavigation);
    } else {
        initNavigation();
    }
}

// 为了兼容模块化和非模块化环境
if (typeof module !== 'undefined') {
    // 暴露到全局对象
window.initNavigation = initNavigation;
window.Navigation = Navigation;
// module.exports = { initNavigation, Navigation };
} else {
    window.Navigation = Navigation;
    window.initNavigation = initNavigation;
}